import type { RouterItem } from '/#/vue-router';
const lazyLoading =
  (name, index = false) =>
  () =>
    /* @vite-ignore */
    import(`/@/views/${name}${index ? '/index' : ''}.vue`);

const importcomponent = function (data, parentName = '') {
  for (const item in data) {
    if (data[item].component) {
      const componentName = data[item].component;
      data[item].component = lazyLoading(componentName);
      if (data[item].children) {
        importcomponent(data[item].children, data[item].name);
      }
      if (parentName) {
        data[item].meta.parent = parentName;
      }
    } else if (data[item].children) {
      importcomponent(data[item].children, data[item].name);
    }
  }
  return data;
};

const generateRoutesFromMenu = function (menu = [], rs: RouterItem = []) {
  for (let i = 0, l = menu.length; i < l; i++) {
    const item: RouterItem = menu[i];
    if (item.path) {
      rs.push(item);
    }
    if (!item.component) {
      generateRoutesFromMenu(item.children, rs);
    }
  }
  return rs;
};

const generateRoutes = (data) => {
  const routeData = JSON.parse(JSON.stringify(data));
  const componentRoute = importcomponent(routeData);
  const routes: RouterItem = generateRoutesFromMenu(componentRoute);
  return routes;
};
export { generateRoutes };
